package com.boyou.sytzc.api;


import android.annotation.SuppressLint;
import android.content.Context;

import com.boyou.sytzc.utils.app.AppConfig;

import java.util.HashMap;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Jbtm on 2017/4/28.
 * 网络请求管理类
 */
public class HttpApiManager {

    private final HashMap<Class, Object> httpApiCache = new HashMap<>();
    private final Retrofit retrofit;

    /**
     * 构造函数
     */
    private HttpApiManager(Context context) {
        String domainUrl = AppConfig.singleton().getServerUrl();
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        retrofit = new Retrofit.Builder()
                .baseUrl(domainUrl.endsWith("/") ? domainUrl : String.format("%s/", domainUrl))
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClientBuilder.build())
                .build();
    }

    /**
     * 获取Api接口服务
     *
     * @param clazz API接口定义
     * @param <T>   API接口定义的泛型类
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T getService(Class<T> clazz) {
        if (httpApiCache.containsKey(clazz))
            return (T) httpApiCache.get(clazz);
        T t = retrofit.create(clazz);
        httpApiCache.put(clazz, t);
        return t;
    }

    @SuppressLint("StaticFieldLeak")
    private static HttpApiManager httpApiManager;

    /**
     * 获取HttpApiManager对象，使用无参数构造函数初始化
     *
     * @param context 上下文对象
     * @return
     */
    @SuppressWarnings("unchecked")
    public static HttpApiManager getInstance(Context context) {
        if (httpApiManager == null) {
            synchronized (HttpApiManager.class) {
                httpApiManager = new HttpApiManager(context);
            }
        }
        return httpApiManager;
    }

    /**
     * 获取API接口服务
     *
     * @param context 上下文对象
     * @param clazzS  API接口
     * @return
     */
    public static <S> S getApiService(Context context, Class<S> clazzS) {
        return getInstance(context).getService(clazzS);
    }

}
